//
//  LXRShowPictureViewController.m
//  01- 百思不得姐
//
//  Created by mac on 16/6/24.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LXRShowPictureViewController.h"
#import "LXRTopicModel.h"
#import "LXRProgressView.h"

#import "UIImageView+WebCache.h"
#import "MBProgressHUD+MJ.h"

@interface LXRShowPictureViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *ScrollView;
/**图片控件*/
@property(nonatomic,weak)UIImageView* imageView;
@property (weak, nonatomic) IBOutlet LXRProgressView *ProgressView;


@end

@implementation LXRShowPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //添加图片控件
    UIImageView* imageView = [[UIImageView alloc]init];
    imageView.userInteractionEnabled = YES;
    [self.ScrollView addSubview:imageView];
    self.imageView = imageView;
    [self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)]];
    
   
    
    //图片宽度
    CGFloat pictureW = LXRScreenW;
    CGFloat pictureH = pictureW * self.model.height / self.model.width;
    //NSLog(@"%@,%zd,%zd",self.model,_model.height,_model.width);
    if (pictureH > LXRScreenH) {//图片显示高度超过一个屏幕,需要滚动查看
        self.imageView.frame = CGRectMake(0, 0, pictureW, pictureH);
        self.ScrollView.contentSize = CGSizeMake(0, pictureH);
    }else{
        self.imageView.size = CGSizeMake(pictureW, pictureH);
        self.imageView.centerY = LXRScreenH*0.5;
    }
    
    //马上显示当前图片的额下载进度
    [self.ProgressView setProgress:self.model.pictureProgress animated:NO];
    //下载图片
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.model.large_image] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        self.ProgressView.hidden = NO;
        [self.ProgressView setProgress:1.0*receivedSize/expectedSize animated:NO];
        
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.ProgressView.hidden = YES;
    }];
    
}

/**点击按钮或者图片跳转回上一界面*/
-(IBAction)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**保存图片*/
- (IBAction)Save {
    
    if (self.imageView.image == nil) {
        [MBProgressHUD showError:@"图片未下载完毕"];
        return;
    }
    
    //将图片写入相册
    UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
/**图片写入状态*/
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        [MBProgressHUD showError:@"保存失败!"];
    }else{
        [MBProgressHUD showSuccess:@"保存成功!"];
    }
}
@end
